var appPath = getAppPath();
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var validFile = false;
var uploader = null;

$(function() {
	$("#queryTypeL").combobox({
		data:[{type_id:0,name:'不限'},{type_id : 1,name : 'IOS版本'},{type_id : 2,name : 'Android版本'},{type_id : 3,name : '一键生成AI插件'}],
		valueField : 'type_id',
		textField : 'name',
		onLoadSuccess:function(){
			$("#queryTypeL").combobox('select',0).combobox('enable');
		}
	});
	$("#queryTypeM").combobox({
		data : [{type_id:0,type_name:'不限'},{type_id : 10,type_name : '测试版'},{type_id : 20,type_name : 'release版'}],
		valueField : 'type_id',
		textField : 'type_name',
		onLoadSuccess:function(){
			$("#queryTypeM").combobox('select',0).combobox('enable');
		}
	});
	$("#queryTypeS").combobox({
		data : [{type_id:-1,type_name:'不限'},{type_id : 0,type_name:'无效'},{type_id : 1,type_name:'有效'}],
		valueField : 'type_id',
		textField : 'type_name',
		onLoadSuccess:function(){
			$("#queryTypeS").combobox('select',-1).combobox('enable');
		}
	});
	initProdVerGrid();
});

function initOSS() {
	if (uploader) {
		return;
	}
	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selFiles', 
	    url : 'http://oss.aliyuncs.com',
		init: {
			PostInit: function() {
				document.getElementById('postFiles').onclick = function() {
		            set_upload_param(uploader, '', false);
		            return false;
				};
			},
			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bHasOne = false;// 一次只能上传一个
				plupload.each(files, function(file) {
					if(bHasOne || !isApk(file.name)) {
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					} else {
						document.getElementById('ossfile').innerHTML += 
	                    	'<div id="'+file.id+'" class="upload_file_info">'+file.name+'('+plupload.formatSize(file.size) +
	                    	')<p class="editUrl1" style="white-space:nowrap;overflow:hidden;"></p>'+
	                    	'<div class="upload_progress"><div class="upload_progress_bar" style="width: 0%">'
	                    	+ '</div></div></div>';
						bHasOne = true;
					}
				});
				if (!bHasOne) {
					$.messager.alert('message','必须是软件应用！','info');
				}     
			},
			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },
			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('p')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0];
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
			},
			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	var finUrl='http://itbour-back.oss-cn-hangzhou.aliyuncs.com/'+g_object_name;
	            	document.getElementById(file.id).getElementsByTagName('p')[0].innerHTML =finUrl;
	            	$("a.editUrl").attr('href',finUrl);
	            	$.messager.alert('message','上传成功','info');
	            }else {
	            	document.getElementById(file.id).getElementsByTagName('p')[0].innerHTML = info.response;
	            	$.messager.alert('message','上传失败','info');
	            }
			}
		}
	});
	uploader.init();
}

function isApk(url) {
    var res, suffix = "";
    var imageSuffixes = ["apk","ipa","exe"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;
    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

var g_object_name = '';
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;
var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
  }
	return str;
}

function getSuffix(filename) {
  var pos = filename.lastIndexOf('.');
  var suffix = '';
  if (pos != -1) {
      suffix = filename.substring(pos);
  }
  return suffix;
}

function calculate_object_name(filename) {
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
	g_object_name = "app/U"+g_userId+"/"+nowStr + randomString(20)+"/"+filename;
}

function set_upload_param(up, filename, ret) {
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
  if (OSS_PARAM.expire < dtNow + 5000) {// 5s
  	var url = appPath+"/itbImg/getOSSToken.action";
      $.get(url, function(data){  
  		if (data && data.signature) { 
  			OSS_PARAM.expire = data.expire;
  			OSS_PARAM.uploadHost = data.uploadHost;
  			OSS_PARAM.accessKeyId = data.accessKeyId;
  			OSS_PARAM.policyBase64 = data.policyBase64;
  			OSS_PARAM.signature = data.signature;
  			OSS_PARAM.flg = true;
  			doUpStart(up, filename, ret);
          } else {
          	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
          }  
      });
  } else {
  	doUpStart(up, filename, ret);
  }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
      calculate_object_name(filename);
  }
  var new_multipart_params = {
      'key' : g_object_name,
      'policy': OSS_PARAM.policyBase64,
      'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
      'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
      'signature': OSS_PARAM.signature,
  };
  up.setOption({
      'url': OSS_PARAM.uploadHost,
      'multipart_params': new_multipart_params
  });
  up.start();
}

function clearUploadList() {
	$(".upload_progress_bar").remove();
	$(".upload_progress").remove();
	$(".upload_file_info").remove();
}

/**初始化 加载数据*/
function initProdVerGrid() {
	$('#ProdVerGrid').datagrid({
		url : appPath + "/itbprodver/pageListProdVerInfo.action",
		height : 'full',
		striped : true,
		fitColumns : true,
		queryParams : getQueryParam(),
		singleSelect : false,
		selectOnCheck : true,
		checkOnSelect : true,
		frozenColumns : [[{field : 'ck',checkbox : 'true',width : 10,align : 'center',sortable : false}]],
		columns : [[{field : 'id',title : '项目ID:',width : 20,align : 'center',sortable : false,}, 
		   {field : 'device',title : '平台分类',width : 40,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					if (value){
						switch(value){
						case 1:return '<font color="red">一键生成ios端</font>';break;
						case 2:return '<font color="#FF7F24">一键生成安卓端</font>';break;
						case 3:return '<font color="blue">一键生成AI插件</font>';break;
						}
					}
					return '未知';
				}
		}, 
		{field : 'ver',title : '版本号',width : 30,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					return value||'<span style="color:red">未知</span>';
				}
		}, 
		{field : 'url',title : '下载地址',width : 70,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					var retUrl = '';
	        		if (rowData.url) {
	        			retUrl = '<a href="' + rowData.url + '" target="_blank">'
	        				+ rowData.url.replace('http://itbour-back.oss-cn-hangzhou.aliyuncs.com','')
	        				+ '</a>';
	        		}
	        	  return retUrl;
			}
		},
		{field : 'release',title : '版本类型',width : 35,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					if(value==10){
						return '<span style="color:#FF34B3;">测试版本</span>';
					}else if(value==20){
						return '<span style="color:#FF34B3;">release版</span>';
					}
				}
		},
		{field : 'chk_freq',title : '检查频率(h)',width : 30,align : 'left',sortable : false,
			formatter : function(value, rowData, rowIndex) {
				return value+'/h' || '<span style="color:red>暂无描述</span>"';
				}
		},
		{field : 'valid',title : '状态',width : 20,align : 'left',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					if(value>0){
						return '<a href="javascript:void(0)" onclick="setValid('+rowData.id+','+value+')" style="color:#2B2B2B;">有效</a>';
					}else{
						return '<a href="javascript:void(0)" onclick="setValid('+rowData.id+','+value+')" style="color:#8B8B83;">无效</a>';
					}
				}
		},
		{field : 'desc',title : '描述',width : 50, align : 'left', sortable : false},
		{field : 'edit',title : '编辑',width : 25, align : 'center',sortable : false,
			formatter : function(value, rowData, rowIndex) {
				return '<a href="javascript:void(0)" onclick="showDetail('+rowData.id+')">修改</a>';
				}
		}, 
		{field : 'create_time',title : '创建时间',width : 55,align : 'center',sortable : false}, 
		{field : 'update_time',title : '更新时间',width : 50,align : 'left',sortable : false}]],
		hideColumn : [ 'user_type' ],
		pagination : true,
		rownumbers : true,
		toolbar : [ {
			text : '新建版本信息',
			iconCls : 'icon-add',
			handler : function() {
				addProdVer();
			}
		}, {
			text : '删除版本信息',
			iconCls : 'icon-cancel',
			handler : function() {
				delProdVer();
			}
		}]
	});
}

/**设置状态是否有效 */
function setValid(id,deValid){
	$("#id").val(id);
	$("#editTypeS").combobox('enable');
	$("#validBtn").show();
	$("#editTypeS").combobox({
		data : [{type_id : 0,type_name:'无效'},{type_id : 1,type_name:'有效'}],
		valueField : 'type_id',
		textField : 'type_name',
		onLoadSuccess:function(){
			$("#editTypeS").combobox('select',deValid).combobox('enable');
		}
	});
	$('#editValid').window({
		title:'设定状态',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#editValid').window('move',{top:20,left:100});
	$('#editValid').window('open');
}

/**取消状态设定*/
function cancelUpValid(){
	$('#editValid').window('close');
}

/**确定 设定状态*/
function doUpValid(){
	var id = $("#id").val();
	var valid = $("#editTypeS").combobox('getValue');
	if(!id ||id.length <= 0){
		$.messager.alert('error','请联系管理员,系统故障','warning');
		return;
	}
	var	 url = appPath +"/itbprodver/updProdVerInfo.action";// 修改
	var sendData={
			"prodVerInfoDto.id":id||'',
			"prodVerInfoDto.valid" : valid || ""
	};
	$.post(url,sendData,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','设定成功','info',function(){
				$('#editValid').window('close');
				doQuery();
			});
		}else {
			$.messager.alert('提示信息','设定失败','warning');
		}
	});
}

/**添加版本信息
 */
function addProdVer() {
	$("#ossfile").html('');
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#id").val('');
	$("#editDesc").val('');
	$("#editTypeM").combobox('enable');
	$("#editTypeS").combobox('enable');
	$("#editTypeL").combobox({
		data:[{type_id : 1,name : 'IOS版本'},{type_id : 2,name : 'Android版本'},{type_id : 3,name : '一键生成AI插件'}],
		valueField : 'type_id',
		textField : 'name',
		onLoadSuccess:function(){
			$("#editTypeL").combobox('select',1).combobox('enable');
		}
	});
	$("#editTypeM").combobox({
		data : [ {type_id : 10,type_name : '测试版'},{type_id : 20,type_name : 'release版'}],
		valueField : 'type_id',
		textField : 'type_name',
		value:10
	});
	$("#editBtn").show();
	$('#editDlg').window({
		title : '新建版本信息',
		iconCls : 'icon-edit',
		modal : true,
		shadow : true,
		collapsible : false,
		minimizable : false,
		maximizable : false
	});

	$('#editDlg').window('move', {
		top : 20,
		left : 20
	});
	$('#editDlg').window('open');
	initOSS();
}

// 确认提交编辑
function doEdit() {
	var id = $("#id").val();
	var device = $("#editTypeL").combobox('getValue');
	var release = $("#editTypeM").combobox('getValue');
	var Checkfreq = $("#editCheckfreq").val();
	var ver = $("#editVer").val();
	var furl=$("p.editUrl1").text(); 
	var desc=$("#editDesc").val();
	
	if (device && Number(device || '0') >=0) {
		if (ver&&ver.length>0) {
				var	 url=appPath + "/itbprodver/addProdVerInfo.action";// 新建
			if (Number(id || '0') > 0) {
				var	 url = appPath +"/itbprodver/updProdVerInfo.action";// 修改
			}
			var sendData = {
				"prodVerInfoDto.id" : id || "",
				"prodVerInfoDto.device" : device || 0,
				"prodVerInfoDto.ver" : ver || "",
				"prodVerInfoDto.release" : release,
				"prodVerInfoDto.chk_freq" : Checkfreq || 0,
				"prodVerInfoDto.url" : furl || "",
				"prodVerInfoDto.desc" : desc || ""
			};
			if (uploader) {
				uploader.destroy();
				uploader = null;
			}
			$.post(url, sendData, function(data) {
				if (data == "ok") {
					$.messager.alert('提示信息', '提交成功', 'info');
					$('#editDlg').window('close');
					doQuery();
				}else {
					$.message.alert("提示信息", "提交失败", 'info');
				}
			});
		} else {
			$.messager.alert('提示信息', '填写版本信息', 'info');
		}
	}else{
		$.messager.alert('提示信息', '请选择平台分类', 'info');
	}
}
/**取消编辑*/
function cancelEdit() {
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
	$('#editDlg').window('close');	
}

/**展示单个信息详情 用于修改*/
function showDetail(id) {
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
	$("#ossfile").html('');
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#id").val(id);
	$("#editTypeM").combobox('enable');
	// 加载数据
	var url = appPath + "/itbprodver/getOneProdVerInfo.action?id="+id;
	$.get(url,function(ret) {
		if (ret && ret.length > 0) {
				var info = ret[0];
				$("#editCheckfreq").val(info.chk_freq || '');
				$("#editVer").val(info.ver||'');
				document.getElementById('ossfile').innerHTML += 
                	'<div class="upload_file_info"><p class="editUrl1" style="white-space:nowrap;overflow:hidden;">'+info.url+'</p>'+
                	'<div class="upload_progress"><div class="upload_progress_bar" style="width: 0%"></div></div></div>';
//				$("a.editUrl").attr('href',info.url);
				$("#editTypeL").combobox({
					data:[{type_id : 1,name : 'IOS版本'},{type_id : 2,name : 'Android版本'},{type_id : 3,name : '一键生成AI插件'}],
					valueField : 'type_id',
					textField : 'name',
					onLoadSuccess:function(){
						$("#editTypeL").combobox('select',info.device).combobox('disable');
					}
				});
				$("#editTypeM").combobox({
					data : [ {type_id : 10,type_name : '测试版'},{type_id : 20,type_name : 'release版'}],
					valueField : 'type_id',
					textField : 'type_name',
					value:info.release
				});
				$("#editDesc").val(info.desc||'');
		}
		});
		$("#editBtn").show();
		$('#editDlg').window({
			title : '版本信息编辑',
			iconCls : 'icon-edit',
			modal : true,
			shadow : true,
			collapsible : false,
			minimizable : false,
			maximizable : false
		});
	
		$('#editDlg').window('move', {
			top : 20,
			left : 20
		});
		$('#editDlg').window('open');
		initOSS();
}

function cancelUpdTmpl() {
	$('#tmplDlg').window('close');
}

/**删除版本*/
function delProdVer() {
	var id = $("#ProdVerGrid").datagrid("getChecked");
	if (!id || id.length == 0) {
		$.messager.alert('提示信息', '请选择需要删除的内容！', 'warning');
		return;
	}
	$.messager.confirm("确认", "确认删除？", function(r) {
		if (r) {
			var ids = "0";
			$.each(id, function(index, item) {
				ids = ids+","+item.id;
			});
			console.log(ids);
			var url = appPath + "/itbprodver/delProdVerInfo.action?ids="+ ids;
			$.post(url, function(data) {
				if (data == "ok") {
					$.messager.alert('提示信息', '删除成功', 'info');
					doQuery();
				} else {
					$.messager.alert('提示信息', '删除失败', 'info');
				}
			});
		}
	});
}

/**获取请求信息
 */
function getQueryParam() {
	var queryObject = {};
	var findTypeL = $("#queryTypeL").combobox('getValue');
	var findTypeM = $("#queryTypeM").combobox('getValue');
	var findTypeS = $("#queryTypeS").combobox('getValue');
	var desc = $("#queryFuncDesc").val();
	if (findTypeL && Number(findTypeL || '0') >= 0)
		queryObject.findTypeL = findTypeL;
	if (findTypeM && Number(findTypeM || '0') >0)
		queryObject.findTypeM = findTypeM;
	if(findTypeS)
		queryObject.findTypeS = findTypeS;//这是区分 是否有父类
	if (desc && desc.length > 0)
		queryObject.findDesc = desc;
	return queryObject;
}


/**查询数据*/
function doQuery(startFlg) {
	$("#ProdVerGrid").datagrid('unselectAll');
	if (startFlg == 1) {
		$("#ProdVerGrid").datagrid('load', getQueryParam());
	} else {
		$("#ProdVerGrid").datagrid('reload', getQueryParam());
	}
}

function fmtCreateTime(value, rowData, rowIndex) {
	if (!value)
		return "";
	var s = new Date(value);
	return rowData.create_time = $.DateUtil.format(s, 'yyyy/MM/dd hh:mm:ss');
}
